package com.luo.config;

import com.luo.pojo.Article;
import com.luo.pojo.RedisCacheEnum;
import com.luo.service.content.ContentService;
import com.luo.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.Set;

@Configuration
@EnableScheduling
public class SchedulingConfig {
    //定时任务
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private ContentService contentService;

    @Scheduled(cron = "0 0 * * * ?") //设置每1小时点将缓存中文章浏览量的数据入库
    @Log(logStr = "定时任务,浏览量缓存存入数据库")
    public void saveViews(){
        //遍历redis中已有的键
        Set<String> keys = redisUtil.keys("/post/*");
        for (String key : keys) {
            if(key.equals("Visit_users")||key.equals("Visit_views")||key.equals("About_views")||key.contains("now_time")){
                continue;
            }else if(key.startsWith("back")){
                continue;
            } else{
                int views = Integer.parseInt((String)redisUtil.get(key));
                Article article = new Article();
                int aid = Integer.parseInt(key.split("/")[2]);
                //根据aid 添加views到数据库
                try{
                  int res =  this.contentService.addArticleViews(aid,views);
                  if(res>0){
                      contentService.delAboutArticlesCache();
                      System.out.println("浏览量入库成功！");
                  }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }

    @Scheduled(cron = "0 0 2 * * ?") //每天凌晨2点执行定时任务，数据放入EleasticSearch
//    @Scheduled(cron = "0 */1 * * * ?")  //测试一下，1分钟执行一次
    @Log(logStr = "定时任务，同步数据库文章信息存入ElasticSearch")
    public void saveArticle(){
        Boolean res = this.contentService.putArticleIntoES();
        if (res){
            System.out.println("Success!");
        }else {
            System.out.println("Failed");
        }
    }


}
